<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拦截器</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>

    <script>
        //Promise
        //设置请求拦截器
        axios.interceptors.request.use(function (config) {   
            console.log("请求拦截器成功! 1-号");
            //config参数就是配置对象
            //这里可以修改config中的参数
            config.params={a:100}; //请求url多了参数:http://localhost:3000/posts?a=100
            return config;
            //throw 'Error 失败了!';
        }, function (error) {
            console.log("请求拦截器失败! 1-号");
            return Promise.reject(error);
        });

        axios.interceptors.request.use(function (config) {
            console.log("请求拦截器成功! 2-号");
            //修改config中的参数
            config.timeout=2000;
            return config;
            //throw 'Error 失败了!';
        }, function (error) {
            console.log("请求拦截器失败! 2-号");
            return Promise.reject(error);
        });


        //设置响应拦截器
        axios.interceptors.response.use(function (response) {
            console.log("响应拦截器成功! 1-号");
            //响应结果是axios默认生成的响应结果
            console.log(response);
            //return response;
            //这里不返回整个axios默认生成的响应结果,只返回它的data数据
            return response.data;
        }, function (error) {
            console.log("响应拦截器失败! 1-号");
            return Promise.reject(error);
        });

        axios.interceptors.response.use(function (response) {
            console.log("响应拦截器成功! 2-号");
            return response;
        }, function (error) {
            console.log("响应拦截器失败! 2-号");
            return Promise.reject(error);
        });

        //发送请求
        axios({
            method:'get',
            url:'http://localhost:3000/posts'
        }).then(response=>{
            console.log("自定义回调处理成功的结果!");
            console.log(response);
        }).catch(reason=>{
            console.log('自定义失败的回调!');
        });


        
    </script>
</body>
</html>